package com.antler.smt.portal.service.impl;

import com.antler.smt.constant.DateTimeConstant;
import com.antler.smt.constant.ResumeConstant;
import com.antler.smt.entity.*;
import com.antler.smt.enums.ResultCodeEnum;
import com.antler.smt.portal.mapper.*;
import com.antler.smt.request.portal.PeopleReq;
import com.antler.smt.response.base.Result;
import com.antler.smt.response.portal.GetPeopleResp;
import com.antler.smt.service.portal.PeopleService;
import com.antler.smt.service.portal.SavePeopleInfoService;
import com.antler.smt.utils.DateUtil;
import com.antler.smt.utils.ReturnResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Optional;


/**
 * @author zhangyi
 * @date 2018/7/11 12:47
 */
@Service
public class PeopleServiceImpl implements PeopleService {


    @Autowired
    private PeopleInfoEntityMapper peopleInfoEntityMapper;

    @Autowired
    private PeopleInfoMapper peopleInfoMapper;

    @Autowired
    private SavePeopleInfoService savePeopleInfoService;

    /**
     * 工作经验
     */
    @Autowired
    private ExperienceInfoMapper experienceInfoMapper;

    @Autowired
    private ExperienceEntityMapper experienceEntityMapper;

    /**
     * 专业技能
     */
    @Autowired
    private ProfessionalSkillInfoMapper professionalSkillInfoMapper;

    @Autowired
    private ProfessionalSkillEntityMapper professionalSkillEntityMapper;


    /**
     * 项目经历
     */
    @Autowired
    private ProjectExpertienceInfoMapper projectExpertienceInfoMapper;

    @Autowired
    private ProjectExpertienceEntityMapper projectExpertienceEntityMapper;

    /**
     * 教育经历
     */
    @Autowired
    private EducationalExperienceInfoMapper educationalExperienceInfoMapper;

    @Autowired
    private EducationalExperienceEntityMapper educationalExperienceEntityMapper;

    /**
     * 将人员的信息录入到数据库中
     *
     * @param req
     * @return
     */
    @Override
    @Transactional
    public Result insertPeopleInfo(PeopleReq req,Long memberId) {
        //创建员工实体
        PeopleInfoEntity peopleInfoEntity = new PeopleInfoEntity();
        //基本信息
        peopleInfoEntity.setMemberId(memberId);
        peopleInfoEntity.setName(req.getName());
        peopleInfoEntity.setAge(req.getAge());
        peopleInfoEntity.setSex(req.getSex());
        peopleInfoEntity.setContact(req.getContact());
        peopleInfoEntity.setIdCard(req.getIdCard());
        //职业状态
        peopleInfoEntity.setProfessionalStatus(req.getProfessionalStatus());
        //工作时间
        peopleInfoEntity.setWorkWeek(req.getWorkWeek());
        peopleInfoEntity.setWorkStartTime(req.getWorkStartTime());
        peopleInfoEntity.setWorkEndTime(req.getWorkEndTime());
        peopleInfoEntity.setWorkRestTime(req.getWorkRestTime());
        peopleInfoEntity.setWorkRestStartTime(req.getWorkStartTime());
        peopleInfoEntity.setWorkRestEndTime(req.getWorkRestEndTime());
        //可工作地点
        peopleInfoEntity.setChoseWordPlace(req.getChoseWordPlace());
        peopleInfoEntity.setProvincial(req.getProvincial());
        peopleInfoEntity.setCity(req.getCity());
        peopleInfoEntity.setCountry(req.getCountry());
        //期望薪资
        peopleInfoEntity.setExpectedSalary(req.getExpectedSalary());
        //所在地
        peopleInfoEntity.setCurrentResidence(req.getCurrentResidence());

        //更改履历状态
        peopleInfoEntity.setStatus(ResumeConstant.SUBMIT_NO_AUDIT);


        //自我介绍
        if(!("").equals(req.getSelfEvaluation()) || null != req.getSelfEvaluation()) {
            peopleInfoEntity.setSelfEvaluation(req.getSelfEvaluation());
        }
        //初始化诚信等级，基本信用等级是60分
        peopleInfoEntity.setIntegrityLevel(req.getIntegrityLevel());

        if(!("").equals(req.getRemarks()) || null != req.getRemarks()) {
            peopleInfoEntity.setRemarks(req.getRemarks());
        }
        peopleInfoEntity.setCreateTime(DateUtil.stampToDate(System.currentTimeMillis()));
        peopleInfoEntity.setUpdateDate(DateUtil.stampToDate(System.currentTimeMillis()));

        //查重
        int count = peopleInfoMapper.getCount(memberId);
        if(count != 0){
            return new Result(ResultCodeEnum.APPEND_DATA_ERROR,"该用户已经存在！");
        }

        int one = peopleInfoMapper.insertSelective(peopleInfoEntity);
        if(one == 0) {
            return new Result(ResultCodeEnum.APPEND_DATA_ERROR,"员工数据插入失败！");
        }else{
            Long id = peopleInfoEntity.getId();
            //开启一个线程存入
            savePeopleInfoService.savePeopleInfo(req,id);
            //写入cookies
            ServletRequestAttributes  requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletResponse response = requestAttributes.getResponse();
            Cookie cookie = new Cookie("isAuthed",String.valueOf(peopleInfoEntity.getStatus()));
            cookie.setMaxAge((int) DateTimeConstant.WEEK_S);
            cookie.setPath("/");
            response.addCookie(cookie);
            return new Result(id);
        }
    }

    /**
     * 更新人员信息 TODO
     *
     * @param req
     * @return
     */
    @Override
    @Transactional
    public Result updatePeopleInfo(PeopleReq req) {

        PeopleInfoEntity peopleInfoEntity = new PeopleInfoEntity();

        peopleInfoEntity.setName(req.getName());
        peopleInfoEntity.setAccount(req.getAccount());
        peopleInfoEntity.setAge(req.getAge());
        peopleInfoEntity.setRemarks(req.getRemarks());
        peopleInfoEntity.setWorkingTime(req.getWorkingTime());
        peopleInfoEntity.setPlaceWork(req.getPlaceWork());
        peopleInfoEntity.setExpectedSalary(req.getExpectedSalary());
        peopleInfoEntity.setCurrentResidence(req.getCurrentResidence());
        peopleInfoEntity.setWorkNowStauts(req.getWorkNowStauts());
        peopleInfoEntity.setProfessionalStatus(req.getProfessionalStatus());
        peopleInfoEntity.setAge(req.getAge());
        peopleInfoEntity.setSex(req.getSex());
        peopleInfoEntity.setIdCard(req.getIdCard());
        peopleInfoEntity.setWorkWeek(req.getWorkWeek());
        peopleInfoEntity.setChoseWordPlace(req.getChoseWordPlace());
        peopleInfoEntity.setContact(req.getContact());
        peopleInfoEntity.setProvincial(req.getProvincial());
        peopleInfoEntity.setCity(req.getCity());
        peopleInfoEntity.setCountry(req.getCountry());
        peopleInfoEntity.setPlaceWork(req.getPlaceWork());
        peopleInfoEntity.setWorkingTime(req.getWorkingTime());
        peopleInfoEntity.setAccount(req.getAccount());
        peopleInfoEntity.setSelfEvaluation(req.getSelfEvaluation());
        peopleInfoEntity.setIntegrityLevel(req.getIntegrityLevel());
        peopleInfoEntity.setWorkNowStauts(req.getWorkNowStauts());
        peopleInfoEntity.setWorkingTime(req.getWorkingTime());
        peopleInfoEntity.setWorkingYears(req.getWorkingYears());
        peopleInfoEntity.setMemberId(req.getMemberId());
        //修改主表
        int i = peopleInfoMapper.updatePeopleSelective(peopleInfoEntity);
        //修改状态判断
        boolean[] flag = new boolean[4];

        //修改从表
        if(i != 0) {
            Long peopleId = peopleInfoMapper.selectId(req.getMemberId());
            req.getExperience().stream()
                    .forEach(e -> {
                            e.setId(e.getId());
                            e.setPeopleInfoId(peopleId);
                        int i1 = experienceEntityMapper.updateByPrimaryKeySelective(e);
                        if(i1 != 0){
                            flag[0] = true;
                        }else{
                            flag[0] = false;
                        }
                    });
            req.getEducationalExperiences().stream()
                    .forEach(e -> {
                        e.setId(e.getId());
                        e.setPeopleInfoId(peopleId);
                        int i1 = educationalExperienceEntityMapper.updateByPrimaryKeySelective(e);
                        if(i1 != 0){
                            flag[1] = true;
                        }else{
                            flag[1] = false;
                        }
                    });
            req.getProfessionalSkills().stream()
                    .forEach(e -> {
                        e.setId(e.getId());
                        e.setPeopleInfoId(peopleId);
                        int i1 = professionalSkillEntityMapper.updateByPrimaryKeySelective(e);
                        if(i1 != 0){
                            flag[2] = true;
                        }else{
                            flag[2] = false;
                        }
                    });
            req.getProjectExpertiences().stream()
                    .forEach(e -> {
                        e.setId(e.getId());
                        e.setPeopleInfoId(peopleId);
                        int i1 = projectExpertienceEntityMapper.updateByPrimaryKeySelective(e);
                        if(i1 != 0){
                            flag[3] = true;
                        }else{
                            flag[3] = false;
                        }
                    });
        }
        for (boolean f : flag){
            if(!f){
                return new Result(ResultCodeEnum.APPEND_DATA_ERROR,"用户更新失败！");
            }
        }
        return ReturnResultUtil.getResult("用户更新成功！","用户更新失败！",i);
    }

    /**
     * 获取当前工人、工程师 实体
     *
     * @param memberId
     * @return
     */
    @Override
    public Result selectPeople(Long memberId) {
        PeopleInfoEntity pe = peopleInfoMapper.selectPeople(memberId);
        boolean present = Optional.ofNullable(pe).isPresent();
        if(!present){
            return new Result(ResultCodeEnum.APPEND_DATA_ERROR,"该用户不是员工用户！");
        }
        GetPeopleResp people = new GetPeopleResp();
        people.setName(pe.getName());
        people.setWorkingYears(pe.getWorkingYears());
        people.setJobName(pe.getJobName());
        people.setExpectedSalary(pe.getExpectedSalary());
        people.setCurrentResidence(pe.getCurrentResidence());
        people.setPlaceWork(pe.getPlaceWork());
        people.setWorkingTime(pe.getWorkingTime());
        people.setWorkStartTime(pe.getWorkStartTime());
        people.setWorkEndTime(pe.getWorkEndTime());
        people.setWorkRestTime(pe.getWorkRestTime());
        people.setWorkRestStartTime(pe.getWorkRestStartTime());
        people.setWorkRestEndTime(pe.getWorkRestEndTime());
        people.setAge(pe.getAge());
        people.setSex(pe.getSex());
        people.setIdCard(pe.getIdCard());
        people.setWorkWeek(pe.getWorkWeek());
        people.setChoseWordPlace(pe.getChoseWordPlace());
        people.setContact(pe.getContact());
        people.setProvincial(pe.getProvincial());
        people.setCity(pe.getCity());
        people.setCountry(pe.getCountry());
        people.setPlaceWork(pe.getPlaceWork());
        people.setWorkingTime(pe.getWorkingTime());
        people.setAccount(pe.getAccount());
        people.setSelfEvaluation(pe.getSelfEvaluation());
        people.setIntegrityLevel(pe.getIntegrityLevel());
        people.setWorkNowStauts(pe.getWorkNowStauts());
        people.setProfessionalStatus(pe.getProfessionalStatus());
        people.setJobName(pe.getName());
        people.setWorkingYears(pe.getWorkingYears());
        people.setStatus(pe.getStatus());
        Long id = pe.getId();

        List<ExperienceEntity> experienceEntities = experienceInfoMapper.selectResume(id);

        List<ProjectExpertienceEntity> projectExpertienceEntities = projectExpertienceInfoMapper.selectResume(id);

        List<EducationalExperienceEntity> educationalExperienceEntities = educationalExperienceInfoMapper.selectResume(id);

        List<ProfessionalSkillEntity> professionalSkillEntities = professionalSkillInfoMapper.selectResume(id);

        people.setExperience(experienceEntities);
        people.setEducationalExperiences(educationalExperienceEntities);
        people.setProfessionalSkills(professionalSkillEntities);
        people.setProjectExpertiences(projectExpertienceEntities);

        if(people != null){
            return new Result(people);
        }else{
            return new Result(ResultCodeEnum.APPEND_DATA_ERROR,"查询失败！");
        }
    }
}
